package top.kaoshanji.p2ch15a;

import java.util.ArrayList;
import java.util.List;

/**
 * 代码清单-p2ch15a-435页a：共享内存示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/23 11:09
 */
public class ShareMemoryDemo {

    private static int shared = 0;

    private static void incrShared() {
        shared ++;
    }

    static class ChildThread extends Thread {
        List<String> list;

        public ChildThread(List<String> list) {
            this.list = list;
        }

        @Override
        public void run() {
            incrShared();
            list.add(Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();

        Thread t1 = new ChildThread(list);
        Thread t2 = new ChildThread(list);

        t1.start();
        t2.start();

        t1.join(); // main 线程 等待 t1 线程执行完
        t2.join();

        System.out.println(shared);
        System.out.println(list);

    }


}
